//
//  BDRefundViewController.m
//  BadBoy
//
//  Created by wen on 2017/7/11.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDRefundViewController.h"
#import "BDComplaintsTableViewCell.h"
#import "BDTextView.h"
#import "BDUserModel.h"

@interface BDRefundViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) BDTextView *textView;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;
@property (nonatomic, strong) UIButton *tousuButton;

@end

@implementation BDRefundViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"申请退款");
    
    [self requestDatasource];
    [self.tableView reloadData];
    
    [[self.tousuButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
        NSString *url = nil;
        if (self.reservation.channel == 0) {
            //支付宝
            url = [NSString stringWithFormat:@"%@payment/ali/refund", KBDBaseURL];
        }else if (self.reservation.channel == 1) {
            //微信
            url = [NSString stringWithFormat:@"%@payment/wechat/refund", KBDBaseURL];
        }
        NSDictionary *para = @{@"id":@(self.reservation.my_id),
                               @"type":@"4"};
        NSString *headValid = [BDUserModel getHeaderValidation];
        RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            [MBManager hideAlert];
            self.reservation.status = 3;
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"退款操作已提交成功，正在等待处理")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:^(NSInteger index) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"退款失败")clickHidden:YES clickBlock:nil];
        }];
    }];
}

- (void)requestDatasource{
    self.datasource = @[ASLocalizedString(@"商家营业但不接待"),
                        ASLocalizedString(@"买多了/买错了"),
                        ASLocalizedString(@"计划有变，没时间消费"),
                        ASLocalizedString(@"联系不上商家"),
                        ASLocalizedString(@"其他")].mutableCopy;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section < 2) {
        return 1;
    }
    return self.datasource.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.datasource.count) {
        return 45;
    }else{
        return 140;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 35)];
    headView.backgroundColor = [UIColor clearColor];
    
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
    label.font = [UIFont systemFontOfSize:15];
    label.tag = 2222;
    [headView addSubview:label];
    
    if (section == 0) {
        label.text = ASLocalizedString(@"套餐名称");
    }else if (section == 1) {
        label.text = ASLocalizedString(@"退还内容");
    }else if (section == 2) {
        label.text = ASLocalizedString(@"退款原因");
    }
    
    [label sizeToFit];
    label.left = 10;
    label.centerY = headView.height / 2.0;
    return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        if (indexPath.row < self.datasource.count) {
            BDComplaintsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"complaintsCell" forIndexPath:indexPath];
            cell.textLabel.text = self.datasource[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.is_Selected = NO;
            if (self.selectedIndexPath != nil) {
                if (indexPath.row == self.selectedIndexPath.row) {
                    cell.is_Selected = YES;
                }
            }
            return cell;
        }else{
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"textViewCell"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"textViewCell"];
                self.textView = [[BDTextView alloc] initWithFrame:CGRectMake(10, 1, kBDScreenWidth - 20, 130)];
                _textView.placeholder = ASLocalizedString(@"请输入其他原因…");
                _textView.placeHolderFont = [UIFont systemFontOfSize:13];
                [cell.contentView addSubview:_textView];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"titleCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"titleCell"];
            
        }
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        if (indexPath.section == 0) {
            cell.textLabel.text = self.reservation.coupon.title;
        }else if (indexPath.section == 1) {
            NSString *string = [NSString stringWithFormat:ASLocalizedString(@"现金：¥%@"), self.reservation.receipt_amount];
            NSMutableAttributedString *attribuString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:[NSString stringWithFormat:@"¥%@", self.reservation.receipt_amount]];
            [attribuString setAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"ff4f00"]} range:range];
            cell.textLabel.attributedText = attribuString;
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < self.datasource.count) {
        self.selectedIndexPath = indexPath;
        [self.tableView reloadData];
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        UITableViewController* tvc=[[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
        [self addChildViewController:tvc];
        [tvc.view setFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, self.tousuButton.top - kBDTopHeight)];
        self.tableView = tvc.tableView;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        [_tableView registerClass:[BDComplaintsTableViewCell class] forCellReuseIdentifier:@"complaintsCell"];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.tableFooterView = [self customTableFooterView];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)customTableFooterView{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 30)];
    
    UIButton *xuzhiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [xuzhiButton setTitle:ASLocalizedString(@"温馨提示：退款将在7个工作日内退回到支付方")forState:UIControlStateNormal];
    [xuzhiButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
    xuzhiButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [xuzhiButton sizeToFit];
    xuzhiButton.left = 10;
    xuzhiButton.centerY = footerView.height / 2.0;
    [footerView addSubview:xuzhiButton];
    
    return footerView;
}

- (UIButton *)tousuButton{
    if (!_tousuButton) {
        self.tousuButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_tousuButton setTitle:ASLocalizedString(@"申请退款")forState:UIControlStateNormal];
        [_tousuButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _tousuButton.backgroundColor = KBDColorBlue;
        _tousuButton.titleLabel.font = [UIFont systemFontOfSize:17];
        _tousuButton.size = CGSizeMake(kBDScreenWidth - 20, 40);
        _tousuButton.bottom = kBDScreenHeight - 10;
        _tousuButton.left = 10;
        _tousuButton.layer.masksToBounds = YES;
        _tousuButton.layer.cornerRadius = 4;
        [self.view addSubview:_tousuButton];
    }
    return _tousuButton;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
